package com.litong.litongjiaoyu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.litong.litongjiaoyu.entity.AccessToken;
import com.litong.litongjiaoyu.entity.WxMssVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName WxPushServiceQcl
 * @Description 微信小程序推送服务
 * @Author jingz
 * @Date 2019/11/15 14:47
 * @Version 1.0
 **/
@Service
public class WxPushServiceQcl {
    private Logger logger = LoggerFactory.getLogger(WxPushServiceQcl.class);

    /**
     * 用来请求微信的get和post
     */
    @Autowired
    private RestTemplate restTemplate ;


    /**
     * 微信小程序推送单个用户
     * @param appid 微信小程序appid
     * @param AppSecret AppSecret
     * @param wxMssVo 需要推送的数据
     * @return
     */
    public JSONObject pushOneUser(String appid, String AppSecret, WxMssVo wxMssVo) {


        //获取access_token
        String access_token = getAccess_token(appid, AppSecret);
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" +
                "?access_token=" + access_token;

        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        String res = responseEntity.getBody();

        JSONObject jsonObject = JSON.parseObject(res);

        if (jsonObject.getInteger("errcode") == 0) {
            logger.info("小程序推送结果={}", res);
        } else {
            logger.error("小程序推送结果={}", res);
        }
        return jsonObject;
    }

    /**
     * 获取access_Token
     * @param appid
     * @param appsecret
     * @return
     */
    public String getAccess_token(String appid, String appsecret) {
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        AccessToken accessToken = new Gson().fromJson(json, AccessToken.class);
        return accessToken.getAccess_token();
    }

}
